package com.zy.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 公司：解耦
 * 1.属性+方法
 */

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }

        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "C").start();

    }
}

class Ticket2 {
    //属性 方法
    private int number = 30;

    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();//加锁
        lock.tryLock();//尝试锁

        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖了" + (number--) + "票，剩余" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
